<template>
  <div class="work-order-manage">
    <h2>工单管理</h2>

    <!-- 搜索条件区域 -->
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="6">
        <el-input v-model="searchParams.playerId" placeholder="玩家ID" clearable @keyup.enter="handleSearch" />
      </el-col>
      <el-col :span="6">
        <el-select v-model="searchParams.status" placeholder="状态">
          <el-option label="待处理" value="待处理" />
          <el-option label="已完成" value="已完成" />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-col>
    </el-row>

    <el-table :data="workOrders" style="width: 100%" border>
      <el-table-column prop="id" label="工单ID" align="center"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center"></el-table-column>
      <el-table-column prop="issueType" label="问题类型" align="center"></el-table-column>
      <el-table-column prop="description" label="问题描述" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template #default="scope">
          <el-date-picker
              v-model="scope.row.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
        <template #default="scope">
          <el-date-picker
              v-model="scope.row.updateTime"
              type="datetime"
              placeholder="选择更新时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <el-button type="primary" @click="showAddWorkOrderDialog">新增工单</el-button>

    <!-- 新增工单对话框 -->
    <el-dialog title="新增工单" v-model="addWorkOrderDialogVisible" width="30%">
      <el-form :model="newWorkOrder">
        <el-form-item label="玩家ID">
          <el-input v-model="newWorkOrder.playerId"></el-input>
        </el-form-item>
        <el-form-item label="问题类型">
          <el-input v-model="newWorkOrder.issueType"></el-input>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input type="textarea" v-model="newWorkOrder.description"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="newWorkOrder.status" placeholder="请选择状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="newWorkOrder.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
              v-model="newWorkOrder.updateTime"
              type="datetime"
              placeholder="选择更新时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addWorkOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addWorkOrder">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑工单对话框 -->
    <el-dialog title="编辑工单" v-model="editWorkOrderDialogVisible" width="30%">
      <el-form :model="currentWorkOrder">
        <el-form-item label="玩家ID">
          <el-input v-model="currentWorkOrder.playerId" disabled></el-input>
        </el-form-item>
        <el-form-item label="问题类型">
          <el-input v-model="currentWorkOrder.issueType"></el-input>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input type="textarea" v-model="currentWorkOrder.description"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentWorkOrder.status" placeholder="请选择状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="currentWorkOrder.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
              v-model="currentWorkOrder.updateTime"
              type="datetime"
              placeholder="选择更新时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editWorkOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateWorkOrder">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

const workOrders = ref([]);
const total = ref(0);          // 总记录数
const currentPage = ref(1);    // 当前页码
const pageSize = ref(10);      // 每页记录数
const searchParams = ref({     // 搜索参数
  playerId: '',
  status: ''
});

const newWorkOrder = ref({
  playerId: '',
  issueType: '',
  description: '',
  status: '待处理',
  createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
});

const currentWorkOrder = ref({
  playerId: '',
  issueType: '',
  description: '',
  status: '',
  createTime: null,
  updateTime: null
});

const addWorkOrderDialogVisible = ref(false);
const editWorkOrderDialogVisible = ref(false);

// 获取工单列表（带分页）
const getWorkOrders = async (page = 1, pageSizeNum = 10) => {
  console.log('>>>> 进入getWorkOrders函数');
  console.log('传入的page参数:', page, '类型:', typeof page);
  console.log('传入的pageSize参数:', pageSizeNum, '类型:', typeof pageSizeNum);

  try {
    const res = await request.get('/customer-service/work-orders', {
      params: {
        page,
        pageSize: pageSizeNum,
        ...searchParams.value
      }
    });

    console.log('API响应状态码:', res.code);
    console.log('API响应数据结构:', res.data);

    if (res.code === 200 && res.data) {
      // 安全获取数据并进行类型检查
      const records = Array.isArray(res.data.records) ? res.data.records : [];
      const totalCount = Number(res.data.total) || 0;
      const currentPageNum = Number(res.data.page) || 1;
      const pageSizeNum = Number(res.data.rows) || 10;

      console.log('数据类型检查:', {
        records: Array.isArray(records),
        total: typeof totalCount === 'number',
        page: typeof currentPageNum === 'number',
        rows: typeof pageSizeNum === 'number'
      });

      workOrders.value = records;
      total.value = totalCount;
      currentPage.value = currentPageNum;
      pageSize.value = pageSizeNum;

      console.log('更新后的数据:', {
        workOrders: workOrders.value.length,
        total: total.value,
        currentPage: currentPage.value,
        pageSize: pageSize.value
      });
    } else {
      ElMessage.error(res.message || '获取工单列表失败');
    }
  } catch (error) {
    console.error('获取工单列表出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    throw error;
  }
};

onMounted(() => {
  console.log('组件挂载，初始化获取工单列表');
  getWorkOrders();
});

// 分页事件处理
const handleSizeChange = (newSize) => {
  console.log('页码大小变更:', newSize, '类型:', typeof newSize);
  getWorkOrders(currentPage.value, newSize);
};

const handleCurrentChange = (newPage) => {
  console.log('页码变更:', newPage, '类型:', typeof newPage);
  getWorkOrders(newPage, pageSize.value);
};

// 搜索功能
const handleSearch = () => {
  console.log('执行搜索:', searchParams.value);
  currentPage.value = 1;
  getWorkOrders(1, pageSize.value);
};

const resetSearch = () => {
  console.log('重置搜索条件');
  searchParams.value = {
    playerId: '',
    status: ''
  };
  handleSearch();
};

// 新增工单
const showAddWorkOrderDialog = () => {
  addWorkOrderDialogVisible.value = true;
};

const addWorkOrder = async () => {
  try {
    const res = await request.post('/customer-service/work-order', {
      ...newWorkOrder.value,
      createTime: dayjs(newWorkOrder.value.createTime).format('YYYY-MM-DD HH:mm:ss'),
      updateTime: dayjs(newWorkOrder.value.updateTime).format('YYYY-MM-DD HH:mm:ss')
    });

    if (res.code === 200) {
      ElMessage.success("新增工单成功");
      await getWorkOrders();
      addWorkOrderDialogVisible.value = false;
      newWorkOrder.value = {
        playerId: '',
        issueType: '',
        description: '',
        status: '待处理',
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      };
    } else {
      ElMessage.error(res.message || '新增工单失败');
    }
  } catch (error) {
    console.error('新增工单出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 编辑工单
const handleEdit = (row) => {
  currentWorkOrder.value = { ...row };
  editWorkOrderDialogVisible.value = true;
};

const updateWorkOrder = async () => {
  try {
    const res = await request.put('/customer-service/work-order', {
      ...currentWorkOrder.value,
      createTime: dayjs(currentWorkOrder.value.createTime).format('YYYY-MM-DD HH:mm:ss'),
      updateTime: dayjs(currentWorkOrder.value.updateTime).format('YYYY-MM-DD HH:mm:ss')
    });

    if (res.code === 200) {
      ElMessage.success("更新工单成功");
      await getWorkOrders();
      editWorkOrderDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || '更新工单失败');
    }
  } catch (error) {
    console.error('更新工单出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除工单
const handleDelete = async (row) => {
  if (confirm(`确定要删除工单 ${row.id} 吗？`)) {
    try {
      const res = await request.delete(`/customer-service/work-order/${row.id}`);

      if (res.code === 200) {
        ElMessage.success("删除工单成功");
        await getWorkOrders();
      } else {
        ElMessage.error(res.message || '删除工单失败');
      }
    } catch (error) {
      console.error('删除工单出错:', error);
      ElMessage.error('网络请求失败，请检查控制台日志');
    }
  }
};

// 格式化时间
const formatDate = (date) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};
</script>

<style scoped>
.work-order-manage h2 {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>